<template>
  <!-- 角色管理 -->
  <div>
    <div class="boderSet">
      <div class="top">
        <el-row>
          <el-col :span="24">
            <div class="grid-content bg-purple-dark">
              <el-breadcrumb separator-class="el-icon-arrow-right">
                <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
                <el-breadcrumb-item>系统设置</el-breadcrumb-item>
                <el-breadcrumb-item>角色管理</el-breadcrumb-item>
              </el-breadcrumb>
            </div>
          </el-col>
        </el-row>
      </div>
      <div class="content">
        <el-row>
          <el-col :span="24">
            <div class="conten-top">
              <span>角色列表</span>
            </div>
          </el-col>
        </el-row>
        <!-- ------------------------------------------------------------------- -->
        <el-row>
          <el-col :span="3">
            <div class="btn-group">
              <el-button type="primary" icon="el-icon-plus" @click="handAddUser" style="padding: 10px;">添加角色</el-button>

            </div>
          </el-col>
          <el-col :span="6">
            <div>
              <el-input placeholder="请输入角色名称" v-model="input2">
                <el-button slot="append" type="primary" @click="searchName">查询</el-button>
              </el-input>
            </div>
          </el-col>

          <el-col :span="15">
            <div class="btn-group">

              <el-dropdown>
                <el-button type="primary" style="background-color: white; color: #3F3F65; border-color: #3F3F65;"
                  @click="exportExcel">导出Excel<i class="el-icon-arrow-down el-icon--right"></i>
                </el-button>
                    <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item>导出全部</el-dropdown-item>
                  <el-dropdown-item>导出选中</el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </div>
          </el-col>
        </el-row>
        <div class="struct-content">
          <el-table ref="multipleTable" :data="getAllRole" tooltip-effect="dark" style="width: 100%" id="educe-table">
            <el-table-column prop="id" label="序号" width="200"  header-align="center" align="center">
            </el-table-column>
            <el-table-column prop="roleName" label="角色名称" width="450" header-align="center" align="center">
            </el-table-column>
            <el-table-column prop="roleDesc" label="角色编号" header-align="center" align="center">
            </el-table-column>

            <el-table-column label="操作" header-align="center" align="center" width="180" fixed="right">
              <template slot-scope="scope">
                <el-button size="mini" type="info" icon="el-icon-edit" circle
                  @click="handEditRole(scope.row.id, scope.row.roleName, scope.row.roleDesc)"></el-button>
                <el-button size="mini" type="warning" icon="el-icon-s-custom" circle
                  @click="rolesConfigure(scope.row.id)"></el-button>
                <el-button size="mini" type="danger" icon="el-icon-delete" circle
                  @click="handDeleteRole(scope.row.id)"></el-button>
              </template>
            </el-table-column>

          </el-table>
          <!-- 分页 -->
          <div class="pagination">
            <el-pagination @current-change="handleCurrentChange" :current-page="currentPage" :page-size="pageSize"
              :total="getroleTotal" background layout="prev, pager, next">
            </el-pagination>
          </div>
        </div>
      </div>
    </div>

    <el-dialog :title="title" :visible.sync="dialogVisible" :width="dialogWidth" :before-close="handleClose"
      :center="isCenter">
      <div v-show="isConfigure">
        <el-tree style=" border-radius: 10px; padding: 28px; margin-left: 15px;" :data="getListPerms"
          :props="defaultProps" :show-checkbox="true" node-key="menuId" @check="checkedBox" ref="tree"
          :default-checked-keys="checkedKeys" check-on-click-node></el-tree>
      </div>
      <div v-if="isEditRole || isAddRole">
        <el-form status-icon :label-position="labelPosition" :rules="rules" ref="formLabelAlign" label-width="80px"
          prop="formLabelAlign" :model="formLabelAlign">
          <el-form-item label="角色姓名" prop="roleName">
            <el-input v-model="formLabelAlign.roleName"></el-input>
          </el-form-item>
          <el-form-item label="角色编号" prop="roleDesc">
            <el-input v-model="formLabelAlign.roleDesc"></el-input>
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handSure">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import { addRole } from "@/api/systemSettings";
import { number } from "echarts";
import { mapActions, mapGetters } from "vuex";
import toExcel from "./../../utils/toExcel";
export default {
  name: 'userConfig',
  data() {
    return {
      isCenter: false, // 判断是否居中
      currentPage: 1, // 当前页
      pageSize: 10, // 每页条数
      input2: "", // 搜索内容
      uid: 0, // 选择的用户id
      dialogVisible: false, // 控制模态框
      isConfigure: false, // 控制是否是角色模态框内容
      isAddRole: false,  // 控制是否是添加模态框内容
      isEditRole: false, // 控制是否是修改模态框内容
      dialogWidth: "30%",
      treeNodes: [],
      checkedKeys: [],
      title: "",
      labelPosition: 'right',
      formLabelAlign: {
        id: 0,
        roleDesc: "",
        roleName: ''
      },
      defaultProps: {
        children: 'children',
        label: 'menuName'
      },
      rules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          { min: 2, max: 6, message: '长度在 2 到 6 个字符', trigger: 'blur' }
        ],
        roleDesc: [
          { required: true, message: "请输入角色编号", trigger: "blur" },
          { type: "string", min: 3, max: 12, message: "编号长度在3-12之间", trigger: "blur" }
        ]
      }
    }
  },
  methods: {
    ...mapActions(["roleAll", 'roleUpdate', "queryListPerms", "queryCurrentRole", "permUpdate", "addRole", "deleteRole"]),
    handDeleteRole(id) { // 删除角色
      console.log();
      if (id == 1 || id == 2 || id == 3) {
        this.$message({
          message: '默认角色无法被删除',
          type: 'warning',
          center: true
        })
        return
      }
      this.$confirm('确认删除？').then(_ => {
        this.deleteRole(id).then(res => {
          if (res.code == 200) {
            this.$message({
              message: '删除成功',
              type: 'success',
              center: true
            })
            this.roleAll({ limit: this.pageSize, name: this.input2, page: this.currentPage })
          }
        })
      })
    },
    handleCurrentChange(currentPage) {//获取页码
      this.currentPage = currentPage;
      console.log('当前页码：', currentPage);
    },
    handAddUser() {
      if (this.$refs.formLabelAlign != undefined) {
        this.$refs.formLabelAlign.resetFields();
      }
      this.isAddRole = true;
      this.isCenter = false;
      this.dialogWidth = "30%"
      this.title = "添加角色"
      this.labelPositio = 'left'
      this.dialogVisible = true
    },
    searchName() {
      this.roleAll({ limit: this.pageSize, name: this.input2, page: this.currentPage })
    },
    handEditRole(id, roleName, roleDesc) {
      // this.isAddRole = false
      this.formLabelAlign.id = id
      this.formLabelAlign.roleDesc = roleDesc
      this.formLabelAlign.roleName = roleName
      this.isConfigure = false
      this.dialogVisible = true
      this.isEditRole = true
      this.title = "编辑角色"
    },
    handleClose(done) {
      this.$confirm('确认关闭？')
        .then(_ => {
          // this.isAddRole = false
          this.isConfigure = false
          this.dialogVisible = false
          this.isEditRole = false
          done();
        })
        .catch(_ => { });
    },
    checkedBox(id, e) { // 选择树形内容
      console.log("id是", id);
      console.log(e.halfCheckedKeys);
      let arr = [];
      let arr1 = [];
      let arr2 = e.halfCheckedKeys;
      arr = this.$refs.tree.getCheckedNodes()
      arr.forEach(element => {
        arr1.push(element.menuId)
      });
      let totalArr = arr1.concat(arr2)
      this.treeNodes = totalArr
      console.log("treeNode", this.treeNodes);
    },
    rolesConfigure(id) { // 配置角色按钮
      let checkTreeNode = []
      let parentNodes = []
      this.queryCurrentRole(id).then(res => {
        this.formLabelAlign.id = id // 获取角色当前id
        this.title = "配置角色"
        this.dialogWidth = "50%"
        this.isEditRole = false
        this.isAddRole = false
        this.isConfigure = true //显示内容
        this.getCurrentRoleList
        this.$nextTick(() => {
          for (let item of this.getCurrentRoleList) {
            let node = this.$refs.tree.getNode(item)
            if (node && node.isLeaf) {
              checkTreeNode.push(item)
            } else if (node) {
              parentNodes.push(node)
            }
          }
          // 设置所有子节点选中，自动回填父节点
          this.$refs.tree.setCheckedKeys(checkTreeNode)
          setTimeout(() => {

            // 未回填的父节点单独设置 
            for (let node of parentNodes) {
              do {
                //应当有状态的父节点在未选中时设置为半选中状态 
                if (!node.checked && !node.indeterminate) {
                  node.indeterminate = true
                }
                // node.indeterminate = true 仅对一个节点进行半选中状态设置，其父节点不能自动级联设置，所以这里循环设置级联父节点状态
                node = node.parent
              } while (node)
            }
            console.log("checkTreeNode", checkTreeNode);
          }, 100)
          // this.checkedKeys = this.getCurrentRoleList
          // this.$refs.tree.setCheckedKeys(this.checkedKeys, true ,false)
        }, 100)
        this.dialogVisible = true
      }) // 发起角色拥有权限请求

      //this.$refs[this.formName].resetFields();
    },
    handSure() { //确定按钮
      if (this.isAddRole) { //添加角色
        this.$refs["formLabelAlign"].validate((valid) => {
          if (valid) {
            this.addRole({ roleDesc: this.formLabelAlign.roleDesc, roleName: this.formLabelAlign.roleName }).then(
              res => {
                if (res.code == 200) {
                  this.$message({
                    message: '添加成功',
                    type: 'success'
                  })
                  this.dialogVisible = false
                  this.roleAll({ limit: this.pageSize, name: this.input2, page: this.currentPage })
                }
              }
            )
          } else {
            console.log('error submit!!');
            return false;
          }
        });
      }


      if (this.isConfigure) { // 配置角色
        this.permUpdate({ ids: this.treeNodes, rid: this.formLabelAlign.id }).then(res => {
          if (res.code == 200) {
            this.dialogVisible = false
            this.queryCurrentRole(0)
            this.$message({
              message: '修改成功',
              type: 'success'
            })
          }
        })
      }
      if (this.isEditRole) {
        // 修改角色角色
        this.roleUpdate({
          id: this.formLabelAlign.id,
          roleDesc: this.formLabelAlign.roleDesc,
          roleName: this.formLabelAlign.roleName
        }).then((res) => {
          if (res.code == 200) {
            this.dialogVisible = false
            this.$message({
              message: '修改成功',
              type: 'success'
            })
            this.roleAll({ limit: this.pageSize, name: this.input2, page: this.currentPage })
          }
        }).catch(e => {
          console.log(e);
          this.dialogVisible = false
        });
      }
    },
    exportExcel() {
      if (this.getAllRole.length < 1) {
        this.$message({
          message: "请选择需要导出的内容",
          type: "error",
          center: true
        })
        return false
      }
      toExcel.getExcel("#educe-table", "角色表数据")
    }
  },
  created() {
    console.log("this", this);
    this.roleAll({ limit: 10, name: "", page: 1 })
    this.queryListPerms();
  },
  mounted() {
    this.queryListPerms();
  },
  computed: {
    ...mapGetters(["getAllRole", 'getroleTotal', "getListPerms", "getCurrentRoleList"])
  }
}
</script>
<style scoped>
.top {
  /* height: 32px; */
  /* border: 1px solid black; */
  padding: 10px 20px 25px 29px;
}

.conten-top {
  padding: 0 32px 15px 40px;
}

.boderSet {
  margin: 0 29px;
  /* margin: 29px; */
  border-radius: 10px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  padding: 30px;
}

.btn-group {
  padding-left: 40px;
  float: right;
}

.struct-content {
  margin-top: 10px;
  width: 100%;
  min-height: 400px;
  border-top: 1px solid rgb(212, 209, 209);
}

.table-center {
  text-align: center !important;
}

.pagination {
  margin-top: 10px;
  float: right;
}

::v-deep .el-input-group {
  line-height: normal;
  display: inline-table;
  width: 100%;
  border-collapse: separate;
  border-spacing: 0;
  margin-left: 10px;
}

::v-deep .el-input-group__append button.el-button {
  border-color: #00000000;
  background-color: #343961;
  color: white;
  border-top: 0;
  border-bottom: 0;
}
</style>
